import Dexie from 'dexie'
import { getUsername } from '@/utils/auth'

const db = new Dexie('workcard')
db.version(1).stores({
  workcard: '[username+workuid], username, workuid, ID, workcard'
})

function saveWorkcard(workcard) {
  const username = getUsername()
  console.log(workcard)

  const ID = workcard.workrelattrs.find(v => v.name === 'ID').value
  console.log(ID)

  if (!db.isOpen()) {
    db.open()
  }
  return db.workcard.put({ 'workuid': workcard.workuid, 'username': username, 'ID': ID, 'workcard': workcard })
}

function getWorkcard(workuid) {
  const username = getUsername()
  if (!db.isOpen()) {
    db.open()
  }
  return db.workcard.where('username').equals(username).and((v) => v.workuid === workuid).first()
}

function getWorklist() {
  const username = getUsername()
  if (!db.isOpen()) {
    db.open()
  }
  return db.workcard.where('username').equals(username).sortBy('ID')
}

function deleteWorkcard(workcard) {
  if (!workcard) {
    return new Promise(
      (resolve, reject) => {
        reject('删除失败，删除的工卡不能为空！')
      }
    )
  }
  const username = getUsername()
  if (!db.isOpen()) {
    db.open()
  }
  return db.workcard.where('[username+workuid]').equals([username, workcard.workuid]).delete()
}

function getTotalWorkcardAmount() {
  return getWorklist().then(
    worklist => {
      return new Promise(
        (resolve) => {
          resolve(worklist.length)
        }
      )
    }
  )
}

function getFinishedWorkcardAmount() {
  return getWorklist().then(
    worklist => {
      return new Promise(
        (resolve) => {
          resolve(worklist.filter(workcard => workcard.workcard.isfinished === 'True').length)
        }
      )
    }
  )
}

export {
  saveWorkcard,
  getWorkcard,
  getWorklist,
  deleteWorkcard,
  getTotalWorkcardAmount,
  getFinishedWorkcardAmount
}
